# coding:utf-8
import os
import uuid
import time
import json
from hashlib import sha1

from enum import Enum

im_app_key = os.environ.get('im_app_key') or '1ad918b19da6e5ae584df1a9ed0aa263'
im_app_secret = os.environ.get('im_app_secret') or 'bbbd74a670ed'

IM_LIST_REDIS_KEY = 'netease_im_token_list'

CS_ACCID = '3'
CS_ACCID2 = '4'
# app系统通知IM id
SYS_IM_NOTIFY_FROM = '8'


class OpeType(object):
    """
    created by chenhj at 2017/8/22
    消息类型, 0-个人消息, 1-群消息
    """
    SINGLE = 0
    GROUP = 1


class MsgType(object):
    """
    created by chenhj at 2017/8/22
    网易云信接口用
    0 表示文本消息,
    1 表示图片，
    2 表示语音，
    3 表示视频，
    4 表示地理位置信息，
    6 表示文件，
    100 自定义消息类型
    """
    TEXT = 0
    PIC = 1
    SOUND = 2
    MEDIA = 3
    LOCATE = 4
    FILE = 6
    SELF = 100


class IMMessageType(Enum):
    """
    created by chenhj at 2017/11/22
    IM消息类型(opc系统记录用)
    """
    # 新订单提醒
    NEW_ORDER = 10
    # 派单提醒
    DISPATCH_ORDER = 11
    # 赠送订单
    TRAINING_ORDER = 12
    # 优先抢单
    BRONZE_DISCOUNT_ORDER = 13
    # 普通聊天
    CHAT = 20
    # 客服
    CLIENT = 40
    # 汇币转账
    TRANSFER = 60


class NeteaseIM(object):
    """
    created by chenhj at 2017/8/21

    """
    def __init__(self, app_key, app_secret):
        """
        created by chenhj at 2017/8/21

        """
        self.app_key = app_key
        self.app_secret = app_secret

    def generate_checksum(self, nonce, cur_time):
        """
        created by chenhj at 2017/8/21

        """
        return sha1((self.app_secret+nonce+cur_time).encode('utf8')).hexdigest()

    def _request(self, api, data, method='post'):
        """
        created by chenhj at 2017/8/22

        """
        import requests
        cur_time = str(int(time.time()))
        nonce = uuid.uuid4().hex
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
            'CurTime': cur_time,
            'AppKey': self.app_key,
            'Nonce': nonce,
            'CheckSum': self.generate_checksum(nonce, cur_time)
        }
        return requests.request(
            method, api, headers=headers, data=data
        )

    def apply_im_token(self, accid=None):
        """
        created by chenhj at 2017/8/22
        创建云信im_token
        """
        # 使用uuid作为accid以保证唯一
        if not accid:
            accid = uuid.uuid4().hex[:32]

        api = 'https://api.netease.im/nimserver/user/create.action'

        data = {
            'accid': accid
        }
        resp = self._request(api, data)
        return resp.json()['info']['token']

    def single_send_text_msg(self, from_, to, msg, key='msg'):
        """
        created by chenhj at 2017/8/22
        发送点对点消息
        """
        api = 'https://api.netease.im/nimserver/msg/sendMsg.action'

        data = {
            'from': from_,
            'to': to,
            'ope': OpeType.SINGLE,
            'type': MsgType.TEXT,
            'body': json.dumps({key: msg})
        }
        resp = self._request(api, data)
        return resp.json()

    def get_user_info(self, accids):
        """
        created by chenhj at 15/03/2018

        """
        api = 'https://api.netease.im/nimserver/user/getUinfos.action'
        resp = self._request(api, {'accids': json.dumps(accids)})
        return resp.json()

    def update_blacklist(self, accid, target_id, relation_type=1, value=1):
        """
        create by ld_wu 2018-04-10
        :param accid:
        :param target_id:
        :param relation_type: 本次操作的关系类型,1:黑名单操作，2:静音列表操作
        :param value: 0:取消黑名单或静音，1:加入黑名单或静音
        :return:
        """
        api = 'https://api.netease.im/nimserver/user/setSpecialRelation.action'
        resp = self._request(
            api,
            dict(
                accid=accid,
                targetAcc=target_id,
                relationType=relation_type,
                value=value
            )
        )
        return resp.json()

    def update_user_info(self, accid, name='', icon='', com='', city='', type=1):
        """
        created by chenhj at 2017/8/23
        """
        api = 'https://api.netease.im/nimserver/user/updateUinfo.action'
        data = {
            'accid': accid,
        }
        if name:
            data['name'] = name
        if icon:
            data['icon'] = icon
        data['ex'] = json.dumps({
            'com': com or '',
            'city': city or '',
            'type': type or 1
        })
        resp = self._request(api, data)
        return resp.json()

    def refresh_im_token(self, accid):
        api = 'https://api.netease.im/nimserver/user/refreshToken.action'
        data = {'accid': accid}
        resp = self._request(api, data)
        return resp.json()['info']['token']

    def batch_sys_msg(self, from_id, to_ids, msg, push_title=''):
        """
        create by ld_wu 2017-11-24
        批量发送点对点自定义系统通知
        :return:
        """
        api = 'https://api.netease.im/nimserver/msg/sendBatchMsg.action'
        data = {
            'fromAccid': from_id,
            'toAccids': json.dumps(to_ids),
            'body': json.dumps(msg),
            'pushcontent': push_title,
            'payload': json.dumps(msg),
            'type': MsgType.SELF            # 自定义消息类型
        }
        resp = self._request(api, data)
        return resp.json()

    def single_sys_msg(self, from_id, to_id, msg, push_title=''):
        """
        create by ld_wu 2017-11-24
        发送自定系统通知
        :return:
        """
        api = 'https://api.netease.im/nimserver/msg/sendMsg.action'
        data = {
            'from': from_id,
            'to': to_id,
            'body': json.dumps(msg),
            'msgtype': MsgType.TEXT,
            'pushcontent': push_title,
            'type': MsgType.SELF,
            'ope': OpeType.SINGLE,
            'option': json.dumps(dict(push=True)),
            'payload': json.dumps(msg),
        }
        resp = self._request(api, data)
        return resp.json()

    def batch_system_notify(self, from_id, to_ids, msg, push_title=''):
        api = 'https://api.netease.im/nimserver/msg/sendBatchAttachMsg.action'
        queue_send_count = 450
        for i in range(0, len(to_ids), queue_send_count):
            send_ids = to_ids[i: i + queue_send_count]
            data = {
                'fromAccid': from_id,
                'toAccids': json.dumps(send_ids),
                'attach': json.dumps(msg),
                'pushcontent': push_title,
            }
            resp = self._request(api, data)
        return True

    def group_info(self, group_id, ope=0):
        """
        create by ld_wu 2018-07-28
        获取群组信息
        :param group_id:
        :param ope:
        :return:
        """
        api = 'https://api.netease.im/nimserver/team/query.action'
        data = dict(
            tids=json.dumps([group_id]),
            ope=ope
        )
        resp = self._request(api, data)
        result = resp.json()
        if result.get('code') == 200:
            [group_info] = result['tinfos']
        else:
            group_info = dict()
        return group_info

    def forbid_talk(self, tid, owner_id):
        """
        created by chenhj at 2018/8/9

        """
        api = 'https://api.netease.im/nimserver/team/muteTlistAll.action'
        data = dict(
            tid=tid,
            owner=owner_id,
            mute=True,
            muteType=1
        )
        resp = self._request(api, data)
        print(resp.json())

    def get_forbid_list(self, tid, owner_id):
        """
        created by chenhj at 2018/8/9

        """
        api = 'https://api.netease.im/nimserver/team/listTeamMute.action'
        data = dict(
            tid=tid,
            owner=owner_id,
        )
        resp = self._request(api, data)
        print(resp.json())

    def add_manager(self, tid, owner_id, members):
        """
        created by chenhj at 2018/8/9
        
        """
        api = 'https://api.netease.im/nimserver/team/addManager.action'
        data = dict(
            tid=tid,
            owner=owner_id,
            members=members
        )
        resp = self._request(api, data)
        print(resp.json())


im_client = NeteaseIM(im_app_key, im_app_secret)


if __name__ == '__main__':
    im_client.apply_im_token()
    # 往ios发送测试消息
    # im_app_key = "211cf33f06ece9b9934e91612362e2b8"
    # im_app_secret = "4557f95f32fa"
    #
    # im_client = NeteaseIM(im_app_key, im_app_secret)
    # im_client.single_sys_msg(3233751, 3362617, dict(
    #     apsField=dict(
    #         alert=dict(
    #             body='测试',
    #             title='测试单发'
    #         ),
    #         message_type=20,
    #         demand_id=35487,
    #         demand_status=10,
    #         action_type=1,
    #     )
    # ), '测试')
